package service

import (
	"sync"
	"time"
	"yun_image/config/user"
	"yun_image/dao"
	"yun_image/entity"
	"yun_image/util"
)

var (
	mutex          sync.Mutex
	defaultPicture = user.DefaultPicture
	defaultRoleId  = user.DefaultRoleId
	defaultState   = user.DefaultState
	defaultMax     = user.DefaultMax
)

// 填充User的Role和RouterNames属性
func fillUser(user *entity.User) error {
	var role entity.Role
	err2 := dao.GetRoleById(&role, user.RoleId)
	if err2 != nil {
		return err2
	}
	var routerNames []string
	err3 := dao.GetRouterNamesByRoleId(&routerNames, user.RoleId)
	if err3 != nil {
		return err3
	}

	user.Role = &role
	user.RouterNames = routerNames
	return nil
}

// Login 根据account和password获取用户信息
func Login(user *entity.User, account string, password string) error {
	err1 := dao.GetUserByAccountByPassword(user, account, password)
	if err1 != nil {
		return err1
	}
	if user.Account != "" {
		err2 := fillUser(user)
		if err2 != nil {
			return err2
		}
		user.Token = util.UserTokenUtil.UpdateToken(user.Account)
	}
	return nil
}

// Register 如果返回错误则说明出错
// 如果user为零值则说明该账号已存在
// 其他情况，注册成功
func Register(user *entity.User, account string, password string, userName string) error {
	//注册服务加互斥锁
	mutex.Lock()
	defer mutex.Unlock()

	var userFind entity.User
	err1 := dao.GetUserByAccount(&userFind, account)
	if err1 != nil {
		return err1
	}
	if userFind.UserName != "" {
		return nil
	}

	user.UserName = userName
	user.Account = account
	user.Password = password
	user.RoleId = defaultRoleId
	user.ProfilePicture = defaultPicture
	user.State = defaultState
	user.RegisterTime = time.Now().UnixMilli()
	user.Number = 0
	user.MaxNumber = defaultMax

	//在数据库中插入用户
	err2 := dao.CreateUser(user)
	if err2 != nil {
		return err2
	}
	//填充用户的属性
	err3 := fillUser(user)
	if err3 != nil {
		return err3
	}

	user.Token = util.UserTokenUtil.UpdateToken(user.Account)
	return nil
}

// GetUserByToken 根据token获取User对象
func GetUserByToken(user *entity.User, token string) error {
	if token == "" {
		return nil
	}
	account := util.UserTokenUtil.GetAccount(token)
	if account == "" {
		return nil
	}
	err1 := dao.GetUserByAccount(user, account)
	if err1 != nil {
		return err1
	}
	err2 := fillUser(user)
	if err2 != nil {
		return err2
	}
	user.Token = util.UserTokenUtil.GetToken(user.Account)
	return nil
}

// UpdateUser 更新user对象，可以更新所有属性
func UpdateUser(user *entity.User) error {
	return dao.UpdateUser(user)
}
